package com.videoweb.service.impl;


import com.videoweb.context.AuthenticationContextHolder;
import com.videoweb.model.LoginUser;
import com.videoweb.service.IUserService;
import com.videoweb.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;


/**
 * 登录校验方法
 *
 * @author lmr
 */
@Component
public class SysLoginService {

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserService userService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
//    public String login(String username, String password, String code, String uuid)
    public String login(String username, String password) {
        //
//        TODO 验证码校验
        // 登录前置校验

        // 用户验证
        Authentication authentication = null;
        try {
//            spring security 安全认证
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);

            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
//            进行权限认证  给权限
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            System.out.println(e);
            throw new RuntimeException(e);
        } finally {

            AuthenticationContextHolder.clearContext();
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        记录日志信息

        // 生成token
        return tokenService.createToken(loginUser);
    }


}



